package com.greenyoung.pwiki.elasticsearch.index.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import com.greenyoung.pwiki.common.consts.ConstElIndex;
import com.greenyoung.pwiki.common.consts.ConstElPipeline;
import com.greenyoung.pwiki.elasticsearch.index.entity.Markdown;
import org.elasticsearch.action.DocWriteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.support.replication.ReplicationResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class IndexUtils {
    private static RestHighLevelClient client;
    private static Logger logger = LoggerFactory.getLogger(IndexUtils.class);

    public IndexUtils(@Qualifier("elasticsearchClient") RestHighLevelClient client) {
        IndexUtils.client = client;
    }

    /**
     * see https://www.elastic.co/guide/en/elasticsearch/client/java-rest/master/java-rest-high-document-index.html
     *
     * @param msg json数据
     * @throws IOException
     */
    public static void IndexMarkdownWithPipeline(String msg) throws IOException {
        Markdown markdown = JSON.parseObject(msg, Markdown.class);
        logger.info("[*] markdown实体数据(除去data)：" + markdown);
        markdown.setData(File2Base64.doIt(markdown.getUrl()));

        //TODO:设置消息队列的重试次数以及错误处理，把type去掉后可以复现
        IndexRequest request = new IndexRequest(ConstElIndex.MARKDOWN_INDEX)
                .type("_doc")
                .id(markdown.getId().toString())
                .setPipeline(ConstElPipeline.PIPELINE_ID)
                .source(JSON.toJSONString(markdown), XContentType.JSON);

        IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT);
        if (indexResponse.getResult() == DocWriteResponse.Result.CREATED) {
            logger.info("[+] md " + markdown.getId() + "第一次被创建");
        } else if (indexResponse.getResult() == DocWriteResponse.Result.UPDATED) {
            logger.info("[*] md " + markdown.getId() + "被更新");
        }

        ReplicationResponse.ShardInfo shardInfo = indexResponse.getShardInfo();
        if (shardInfo.getFailed() > 0) {
            for (ReplicationResponse.ShardInfo.Failure failure :
                    shardInfo.getFailures()) {
                String reason = failure.reason();
                logger.error("[!] 索引md " + markdown.getId() + " 失败，这是el的原因：" + reason);
            }
        }
    }

}
